<template>
  <a-layout class="course-learn-container">
    <GlobalHeader/>
    <a-layout-content class="content">
      <a-row :gutter="24">
        <!-- 左侧视频播放区域 -->
        <a-col :span="16">
          <div class="video-section">
            <div class="video-player">
              <video
                ref="videoPlayer"
                :src="currentLesson?.videoUrl"
                autoplay
                muted
                preload="metadata"
                controls
                style="width: 100%; height: 500px;"
                @error="onVideoError"
                @timeupdate="onTimeUpdate"
                @seeking="onSeeking"
                @seeked="onSeeked"
              >
                您的浏览器不支持视频播放
              </video>
            </div>
            <div style="margin-top: 12px;">
              今日累计观看：{{ Math.floor(getTodayTotalWatched() / 60) }} 分钟
            </div>
          </div>

          <a-tabs default-active-key="ai-doc">
            <a-tab-pane key="ai-doc" tab="AI文档总结">
              <div class="ai-doc-section" style="background: #fff; padding: 16px; border-radius: 8px; margin-bottom: 16px;">
                <div class="section-header"
                  style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
                  <h3>AI生成文档</h3>
                  <a-button type="primary" @click="generateAIDoc" :disabled="!currentLesson">总结视频</a-button>
                </div>
                <div v-if="aiDocLoading">
                  <a-spin tip="AI正在生成文档，请稍后..." />
                </div>
                <div v-else-if="aiDocContent">
                  <a-alert type="success" show-icon message="AI文档生成成功" style="margin-bottom: 8px;" />
                  <MarkdownRenderer :jump-to-time="jumpToTime" :markdown="aiDocContent" style="background: #f6f8fa; padding: 32px; border-radius: 4px; min-height: 80px;"/>
                </div>
                <div v-else style="color: #999;">点击"总结视频"按钮，AI将为您生成当前视频的文档总结。</div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="note" tab="课程笔记">
              <div class="notes-section">
                <div class="section-header">
                  <h3>课程笔记</h3>
                  <div>
                    <a-button style="margin-right: 8px;" @click="copyFromAIDoc">从文档复制</a-button>
                    <a-button type="primary" @click="tSaveNote">保存笔记</a-button>
                  </div>
                </div>
                <div class="notes-md-row">
                  <div class="notes-md-editor">
                    <textarea
                      v-model="noteContent"
                      placeholder="在这里用Markdown格式记录您的学习笔记..."
                      rows="16"
                      @keydown="handleNoteTab"
                      @keydown.ctrl.s.prevent="onCtrlS"
                      @scroll="onTextareaScroll"
                      @input="onTextareaInput"
                      ref="noteTextareaRef"
                      style="height: 400px; resize: none; width: 100%; font-size: 15px; line-height: 1.6; border: 1px solid #d9d9d9; border-radius: 4px; padding: 8px; box-sizing: border-box;"
                    />
                  </div>
                  <div class="notes-md-preview">
                    <div style="margin-bottom: 8px; color: #888; font-size: 13px; text-align:left;">实时预览</div>
                    <div
                      ref="previewRef"
                      class="notes-md-preview-scroll"
                      style="background: #f6f8fa; padding: 16px; border-radius: 4px; min-height: 80px; height: 400px; overflow: auto;"
                      @scroll="onPreviewScroll"
                    >
                      <MarkdownRenderer :markdown="noteContent" :jump-to-time="jumpToTime" />
                    </div>
                  </div>
                </div>
              </div>
            </a-tab-pane>
            <a-tab-pane key="work" tab="AI生成题目">
                <AssignmentPage
                  :video-id="videoId"
                  @answer-change="emit('answer-change')"/>
            </a-tab-pane>
          </a-tabs>

        </a-col>

        <!-- 右侧章节导航 -->
        <a-col :span="8">
          <!-- 课程章节导航 -->
          <div class="chapter-navigation">
            <div class="course-info">
              <h3>{{ courseInfo?.title || '课程标题' }}</h3>
              <p>{{ courseInfo?.description || '课程描述' }}</p>
            </div>
            <div class="chapter-list">
              <div v-for="chapter in courseInfo?.outlineList" :key="chapter.id" class="chapter-item">
                <div class="chapter-header" @click="toggleChapter(chapter.id)">
                  <span class="chapter-title">{{ chapter.title }}</span>
                  <a-icon :type="expandedChapters.includes(chapter.id) ? 'up' : 'down'" />
                </div>
                <div v-show="expandedChapters.includes(chapter.id)" class="lesson-list">
                  <div
                    v-for="lesson in chapter.children"
                    :key="lesson.id"
                    class="lesson-item"
                    :class="{
                      'active': currentLesson?.id === lesson.id,
                      'has-video': lesson.filePath,
                      'no-video': !lesson.filePath
                    }"
                    @click="selectLesson(lesson)"
                  >
                    <div class="lesson-info">
                      <div class="lesson-title">{{ lesson.title }}</div>
                      <div class="lesson-meta">
                        <span v-if="lesson.filePath" class="video-indicator">📹</span>
                        <span v-else class="no-video-indicator">⏸️</span>
                        <span class="lesson-duration">{{ lesson.filePath ? '可播放' : '暂无视频' }}</span>
                      </div>
                    </div>
                    <div class="lesson-status">
                      <a-icon v-if="currentLesson?.id === lesson.id" type="play-circle" style="color: #1890ff;" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!--
          <div class="ai-assistant-section">
            <div class="section-header">
              <h3>AI学习助手</h3>
            </div>
             新增：快速操作圆形按钮组
            <div class="quick-actions-circle">
              <div class="quick-action-item">
                <a-button shape="circle" type="primary" @click="takeAssignment">
                  <EditOutlined />
                </a-button>
                <div class="quick-action-label">做作业</div>
              </div>
              <div class="quick-action-item">
                <a-button shape="circle" @click="takeExam">
                  <FileDoneOutlined />
                </a-button>
                <div class="quick-action-label">参加考试</div>
              </div>
              <div class="quick-action-item">
                <a-button shape="circle" @click="downloadNotes">
                  <FileTextOutlined />
                </a-button>
                <div class="quick-action-label">下载笔记</div>
              </div>
              <div class="quick-action-item">
                <a-button shape="circle" @click="downloadCode">
                  <CodeOutlined />
                </a-button>
                <div class="quick-action-label">下载源码</div>
              </div>
            </div>
            <div class="ai-chat">
              <div class="chat-messages">
                <div v-for="message in chatMessages" :key="message.id" class="message" :class="message.type">
                  <div class="message-content">{{ message.content }}</div>
                  <div class="message-time">{{ message.time }}</div>
                </div>
              </div>
              <div class="chat-input">
                <a-input-search v-model:value="chatInput" placeholder="向AI助手提问..." enter-button="发送"
                                @search="sendMessage" />
              </div>
            </div>
          </div>
          -->

        </a-col>
      </a-row>
    </a-layout-content>
  </a-layout>
</template>

<script setup lang="ts">
import { onMounted, ref, watch, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getSummary, summarizeVideo } from '@/api/videoController.ts'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'
import { EditOutlined, FileDoneOutlined, FileTextOutlined, CodeOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { getCourseBaseById } from '@/api/bizCourseOutlinesController.ts'
import GlobalHeader from '@/components/layout/GlobalHeader.vue'
import { awardVideoWatchPoints } from '@/api/taskActionController'

// 定义接口类型
interface Chapter {
  id: number
  title: string
  parentId: number | null
  videoId: number | null
  filePath: string | null
  sortOrder: number
  children: Lesson[] | null
}

interface Lesson {
  id: number
  title: string
  parentId: number
  videoId: number | null
  filePath: string | null
  sortOrder: number
  children: null
}

interface CurrentLesson {
  id: number
  title: string
  videoId: string
  videoUrl: string
  description?: string
  duration?: string
  progress?: number
  outlineId: number // 新增，保证随时可用
}

const route = useRoute()
const router = useRouter()

// 响应式数据
const activeChapters = ref(['1'])
const currentLesson = ref<CurrentLesson | null>(null)
const noteContent = ref('')
const currentNote = ref<any>(null)
const chatInput = ref('')
const chatMessages = ref([
  {
    id: 1,
    type: 'ai',
    content: '您好！我是您的AI学习助手，有什么问题可以随时问我。',
    time: '14:30'
  }
])

const videoPlayer = ref<HTMLVideoElement | null>(null)
// 课程信息
const courseInfo = ref<any>(null)
// 章节展开状态
const expandedChapters = ref<number[]>([])

// 视频相关
const videoUrl = ref('')
const videoId = ref('')

// 监听videoId变化，自动加载AI文档
watch(videoId, (newVideoId, oldVideoId) => {
  if (newVideoId && newVideoId !== oldVideoId) {
    // 延迟一点时间确保其他数据都已更新
    setTimeout(() => {
      loadAIDoc()
    }, 100)
  }
})

// 跳转到指定时间
const jumpToTime = (timeStr: string) => {
  const [h, m, s] = timeStr.split(':').map(Number);
  const totalSeconds = h * 3600 + m * 60 + s;

  if (videoPlayer.value) {
    window.scrollTo({ top: 0, behavior: 'smooth' });
    videoPlayer.value.currentTime = totalSeconds;
    videoPlayer.value.play();
  }
};

const aiDocContent = ref('')
const aiDocLoading = ref(false)

// 学习统计
const todayStudyTime = ref(45)
const weekStudyTime = ref(320)
const continuousDays = ref(7)

// 方法
const setCurrentLessonById = (lessonId: string | number | undefined) => {
  if (!courseInfo.value?.outlineList) return
  for (const chapter of courseInfo.value.outlineList) {
    if (chapter.children && chapter.children.length > 0) {
      for (const lesson of chapter.children) {
        if (lesson.filePath) {
          if (!lessonId) {
            // 没有outlineId，默认第一个有视频的小节
            setCurrentLesson(lesson)
            // 展开当前章节
            if (!expandedChapters.value.includes(chapter.id)) {
              expandedChapters.value.push(chapter.id)
            }
            return
          } else if (lesson.id == lessonId) {
            setCurrentLesson(lesson)
            // 展开当前章节
            if (!expandedChapters.value.includes(chapter.id)) {
              expandedChapters.value.push(chapter.id)
            }
            return
          }
        }
      }
    }
  }
}

const setCurrentLesson = (lesson: Lesson) => {
  if (!lesson.filePath) {
    return
  }
  currentLesson.value = {
    id: lesson.id,
    outlineId: lesson.id, // 新增，保证随时可用
    title: lesson.title,
    videoId: lesson.videoId?.toString() || '',
    videoUrl: import.meta.env.VITE_VIDEO_BASE_URL + lesson.filePath,
  }
  videoUrl.value = currentLesson.value.videoUrl
  videoId.value = currentLesson.value.videoId
}

const selectLesson = (lesson: Lesson) => {
  setCurrentLesson(lesson)
  router.push(`/course/learn/${route.params.courseId}/${lesson.id}`)
}


// 视频加载错误事件
const onVideoError = (event: Event) => {
  const target = event.target as HTMLVideoElement
}

// 章节展开/收起
const toggleChapter = (chapterId: number) => {
  const index = expandedChapters.value.indexOf(chapterId)
  if (index > -1) {
    expandedChapters.value.splice(index, 1)
  } else {
    expandedChapters.value.push(chapterId)
  }
}

// 加载AI文档
const loadAIDoc = async () => {
  if (!videoId.value) {
    return
  }
  if (!userInfo.value?.userId) {
    return
  }
  try {
    const res = await getSummary({
      "videoId": videoId.value,
      "userId": userInfo.value.userId.toString(),
      "outlineId": currentLesson.value ? currentLesson.value.outlineId : undefined,
    })
      // console.log('加载AI文档请求参数:', {
      //   videoId: videoId.value,
      //   userId: userInfo.value.userId,
      //   outlineId: currentLesson.value ? currentLesson.value.outlineId : undefined,
      // });

    // console.log('AI文档请求结果:', res)

    if (res.data.success) {
      aiDocContent.value = res.data.data
      // console.log('AI文档加载成功，内容长度:', res.data.data?.length || 0)
    } else {
      // console.log('AI文档请求失败:', res.data)
      aiDocContent.value = '' // 清空之前的内容
    }
  } catch (error) {
    // console.error('加载AI文档失败:', error)
    aiDocContent.value = '' // 清空之前的内容
  }
}

const tSaveNote = async () => {
  if (!currentLesson.value) return;
  // 先查有没有已有笔记
  const getRes = await getNote({
    createBy: userInfo.value.userId,
    outlineId: currentLesson.value.outlineId,
  });
  let noteId = getRes.data.data?.id;
  const res = await saveNote({
    id: noteId, // 有id就传id，没有就新增
    content: noteContent.value,
    createBy: userInfo.value.userId,
    outlineId: currentLesson.value.outlineId,
  });
  if (res.data.code == 0) {
    message.success('保存成功');
    if (res.data.data) {
      currentNote.value = res.data.data;
    }
  } else {
    message.error('保存失败');
  }
}

const sendMessage = (message: string) => {
  if (!message.trim()) return

  // 添加用户消息
  chatMessages.value.push({
    id: Date.now(),
    type: 'user',
    content: message,
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  })

  // 模拟AI回复
  setTimeout(() => {
    chatMessages.value.push({
      id: Date.now() + 1,
      type: 'ai',
      content: `关于"${message}"的问题，我来为您详细解答...`,
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
    })
  }, 1000)

  chatInput.value = ''
}

const generateAIDoc = async () => {
  if (!currentLesson.value || !videoId.value) return

  aiDocLoading.value = true
  try {
    const res = await summarizeVideo({
      "videoId": videoId.value,
      "userId": userInfo.value.userId,
      "outlineId": currentLesson.value ? currentLesson.value.outlineId : undefined,
    })

    if (res.data.success) {
      aiDocContent.value = res.data.data
    }
  } catch (error) {
    // console.error('生成AI文档失败:', error)
  } finally {
    aiDocLoading.value = false
  }
}

const takeAssignment = () => {
  router.push(`/course/${videoId.value}/assignment`)
}

const takeExam = () => {
  router.push(`/course/${route.params.id}/exam`)
}

const downloadNotes = () => {
  console.log('下载笔记')
}

const downloadCode = () => {
  console.log('下载源码')
}

// 处理Tab键插入空格
const handleNoteTab = (e: KeyboardEvent) => {
  if (e.key === 'Tab') {
    e.preventDefault();
    const textarea = e.target as HTMLTextAreaElement;
    const start = textarea.selectionStart;
    const end = textarea.selectionEnd;
    const value = noteContent.value;
    // 插入制表符
    noteContent.value = value.substring(0, start) + '\t' + value.substring(end);
    // 设置光标位置
    nextTick(() => {
      textarea.selectionStart = textarea.selectionEnd = start + 1;
    });
  }
};

// Ctrl+S快捷键保存笔记
const onCtrlS = (e: KeyboardEvent) => {
  e.preventDefault();
  saveNote();
};

// 从AI文档复制到笔记
import { message } from 'ant-design-vue'
const copyFromAIDoc = () => {
  if (!aiDocContent.value) {
    message.warning('AI文档还未生成哦')
    return
  }
  noteContent.value = noteContent.value + (noteContent.value ? '\n' : '') + aiDocContent.value
  message.success('已追加AI文档内容到笔记')
}

// 双向滚动同步
import { ref as vueRef, watch as vueWatch } from 'vue';
import { getNote, saveNote } from '@/api/bizMediaDocController.ts'
import AssignmentPage from '@/components/course/AssignmentPage.vue'
const noteTextareaRef = vueRef<HTMLTextAreaElement | null>(null);
const previewRef = vueRef<HTMLElement | null>(null);
let activeScrollSource: 'textarea' | 'preview' | null = null;
let scrollSyncTimeout: any = null;

const onTextareaScroll = () => {
  if (activeScrollSource === 'preview') return;
  activeScrollSource = 'textarea';
  const textarea = noteTextareaRef.value;
  const preview = previewRef.value;
  if (textarea && preview) {
    const percent = textarea.scrollTop / (textarea.scrollHeight - textarea.clientHeight);
    const previewScroll = (preview.scrollHeight - preview.clientHeight) * percent;
    preview.scrollTop = previewScroll;
  }
  clearTimeout(scrollSyncTimeout);
  scrollSyncTimeout = setTimeout(() => { activeScrollSource = null; }, 100);
};

const onPreviewScroll = () => {
  if (activeScrollSource === 'textarea') return;
  activeScrollSource = 'preview';
  const textarea = noteTextareaRef.value;
  const preview = previewRef.value;
  if (textarea && preview) {
    const percent = preview.scrollTop / (preview.scrollHeight - preview.clientHeight);
    const textareaScroll = (textarea.scrollHeight - textarea.clientHeight) * percent;
    textarea.scrollTop = textareaScroll;
  }
  clearTimeout(scrollSyncTimeout);
  scrollSyncTimeout = setTimeout(() => { activeScrollSource = null; }, 100);
};

// 高亮当前行
const activeLine = vueRef(1);
const updateActiveLine = () => {
  const textarea = noteTextareaRef.value;
  if (!textarea) return;
  const value = textarea.value;
  const selectionStart = textarea.selectionStart;
  // 计算光标前有多少个换行符
  const before = value.slice(0, selectionStart);
  activeLine.value = before.split(/\r?\n/).length;
};
const onTextareaInput = () => {
  updateActiveLine();
};
// 在滚动和点击时也更新
noteTextareaRef.value && noteTextareaRef.value.addEventListener('click', updateActiveLine);
// 在mounted后自动高亮第一行
onMounted(() => {
  updateActiveLine();
});
// 在每次noteContent变化时自动更新高亮行
vueWatch(noteContent, () => { updateActiveLine(); });

// 用户信息
const userInfo = ref<any>(null)

// 检查用户登录状态
const checkUserLogin = () => {
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    userInfo.value = JSON.parse(storedUserInfo)
  }
  // console.log(userInfo.value)
}

const loadCourseAndLesson = async (courseId: string | number, outlineId: string | number | undefined) => {
  checkUserLogin()
  // console.log('课程ID:', courseId)
  // console.log('大纲ID:', outlineId)
  // 获取课程信息
  let res = await getCourseBaseById({ id: Number(courseId) })
  if (res.data.code == 0 && res.data.data) {
    courseInfo.value = res.data.data
    // console.log('courseInfo', courseInfo.value)
    setCurrentLessonById(outlineId)
  }
}

const loadNoteInfo = async (userId: number, outlineId: number) => {
  const res = await getNote({
    createBy: userId,
    outlineId: outlineId,
  })
  if (res.data.code == 0 && res.data.data) {
    currentNote.value = res.data.data
    noteContent.value = res.data.data.content || (currentLesson.value ? `# ${currentLesson.value.title}\n` : '# 我的课程笔记\n')
  } else {
    currentNote.value = null
    noteContent.value = currentLesson.value ? `# ${currentLesson.value.title}\n` : '# 我的课程笔记\n'
  }
}

// ========== 视频观看积分相关 ==========
const videoWatchedSeconds = ref({})
const lastTime = ref(0)
let isSeeking = false
const thresholds = [100, 300, 500]
const rewarded = ref({ 100: false, 300: false, 500: false })

// 获取今天的key
const getTodayKey = () => new Date().toISOString().split('T')[0]

// 只存储今日数据
const loadTodayData = () => {
  const todayKey = getTodayKey()
  const saved = localStorage.getItem('videoWatchedSeconds_' + todayKey)
  videoWatchedSeconds.value = saved ? JSON.parse(saved) : {}
  // 积分奖励状态
  const savedRewarded = localStorage.getItem('videoRewarded_' + todayKey)
  rewarded.value = savedRewarded ? JSON.parse(savedRewarded) : { 100: false, 300: false, 500: false }
}

const saveTodayData = () => {
  const todayKey = getTodayKey()
  localStorage.setItem('videoWatchedSeconds_' + todayKey, JSON.stringify(videoWatchedSeconds.value))
  localStorage.setItem('videoRewarded_' + todayKey, JSON.stringify(rewarded.value))
}

// 计算今日总时长
const getTodayTotalWatched = () => {
  return Object.values(videoWatchedSeconds.value).reduce((a, b) => a + b, 0)
}

onMounted(() => {
  loadTodayData()
})

function onVideoChange(newVideoId) {
  lastTime.value = 0
}

function onTimeUpdate(e) {
  if (isSeeking || !currentLesson.value?.videoId) return
  const video = e.target
  const current = Math.floor(video.currentTime)
  const vid = currentLesson.value.videoId
  if (!videoWatchedSeconds.value[vid]) {
    videoWatchedSeconds.value[vid] = 0
  }
  if (current > lastTime.value) {
    videoWatchedSeconds.value[vid] += current - lastTime.value
    saveTodayData()
  }
  lastTime.value = current

  // 只统计今日
  const todayTotalWatched = getTodayTotalWatched()
  for (const t of thresholds) {
    if (todayTotalWatched >= t && !rewarded.value[t]) {
      sendPoints(t, todayTotalWatched)
    }
  }
}

function onSeeking() { isSeeking = true }
function onSeeked(e) {
  isSeeking = false
  lastTime.value = Math.floor((e.target).currentTime)
}

async function sendPoints(threshold, totalWatched) {
  rewarded.value[threshold] = true
  saveTodayData()
  try {
    const res = await awardVideoWatchPoints({
      userId: userInfo.value?.userId,
      watchedSeconds: totalWatched,
      threshold
    })
    if (res.data && res.data.code === 0) {
      message.success(res.data.data || `今日观看满${threshold}秒，获得积分！`)
    } else {
      message.warning(res.data.message || '积分已领取或发放失败')
    }
  } catch (e) {
    message.error('积分发放失败')
  }
}

watch(() => currentLesson.value?.videoId, (newId) => {
  if (newId) onVideoChange(newId)
})

onMounted(async () => {
  const courseId = Array.isArray(route.params.courseId) ? route.params.courseId[0] : route.params.courseId || ''
  const outlineId = Array.isArray(route.params.outlineId) ? route.params.outlineId[0] : route.params.outlineId
  loadCourseAndLesson(courseId, outlineId)
  if (userInfo.value?.userId && outlineId) {
    loadNoteInfo(Number(userInfo.value.userId), Number(outlineId))
  }
})

watch(
  () => [route.params.courseId, route.params.outlineId],
  ([newCourseId, newOutlineId], [oldCourseId, oldOutlineId]) => {
    const courseId = Array.isArray(newCourseId) ? newCourseId[0] : newCourseId || ''
    const outlineId = Array.isArray(newOutlineId) ? newOutlineId[0] : newOutlineId
    loadCourseAndLesson(courseId, outlineId)
  }
)

// 监听currentLesson变化，自动加载对应笔记
watch(currentLesson, (newLesson) => {
  if (userInfo.value?.userId && newLesson?.outlineId) {
    loadNoteInfo(Number(userInfo.value.userId), Number(newLesson.outlineId))
  }
})
</script>

<style scoped>
.course-learn-container {
  min-height: 100vh;
}

.content {
  padding: 24px;
  background: #f5f5f5;
}

.video-section {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
}

.video-player {
  background: #000;
}

.video-placeholder {
  height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lesson-info {
  padding: 16px;
}

.lesson-info h2 {
  margin-bottom: 8px;
  color: #333;
}

.lesson-info p {
  color: #666;
  margin-bottom: 12px;
}

.lesson-meta {
  display: flex;
  align-items: center;
  gap: 16px;
  color: #666;
  font-size: 14px;
}

.notes-section,
.ai-assistant-section {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.ai-chat {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  height: 35vh; /* 调整为35vh，更合适的高度 */
  display: flex;
  flex-direction: column;
}

.chat-messages {
  height: calc(100% - 60px); /* 减去输入框高度 */
  overflow-y: auto;
  padding: 16px;
  flex: 1;
}

/* 自定义聊天区域滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.message {
  margin-bottom: 12px;
}

.message.user {
  text-align: right;
}

.message.ai {
  text-align: left;
}

.message-content {
  display: inline-block;
  max-width: 70%;
  padding: 8px 12px;
  border-radius: 8px;
  background: #f0f0f0;
  word-wrap: break-word;
}

.message.user .message-content {
  background: #1890ff;
  color: #fff;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 章节导航样式 */
.chapter-navigation {
  background: #fff;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
  height: 65vh; /* 调整为65vh，更合适的高度 */
  display: flex;
  flex-direction: column;
}

.course-info {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  flex-shrink: 0; /* 防止压缩 */
}

.course-info h3 {
  margin-bottom: 8px;
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.course-info p {
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 0;
  font-size: 14px;
  line-height: 1.5;
}

.chapter-list {
  padding: 0;
  flex: 1; /* 占据剩余空间 */
  overflow-y: auto; /* 垂直滚动 */
  overflow-x: hidden; /* 隐藏水平滚动 */
}

/* 自定义滚动条样式 */
.chapter-list::-webkit-scrollbar {
  width: 6px;
}

.chapter-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chapter-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chapter-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.chapter-item {
  border-bottom: 1px solid #f0f0f0;
}

.chapter-item:last-child {
  border-bottom: none;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  cursor: pointer;
  color: #333;
  font-weight: 500;
  transition: background-color 0.3s ease;
  background: #fafafa;
}

.chapter-header:hover {
  background: #f0f0f0;
}

.chapter-title {
  flex-grow: 1;
  margin-right: 10px;
  font-size: 15px;
}

.lesson-list {
  background: white;
}

.lesson-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  border-radius: 0;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.lesson-item:hover {
  background: #f8f9fa;
  border-left-color: #1890ff;
}

.lesson-item.active {
  background: #e6f7ff;
  border-left-color: #1890ff;
  color: #1890ff;
}

.lesson-item.has-video {
  cursor: pointer;
}

.lesson-item.no-video {
  cursor: not-allowed;
  opacity: 0.6;
}

.lesson-item.has-video .lesson-info .lesson-duration {
  color: #52c41a;
}

.lesson-item.no-video .lesson-info .lesson-duration {
  color: #999;
}

.lesson-item .lesson-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex-grow: 1;
}

.lesson-item .lesson-title {
  font-weight: 500;
  font-size: 14px;
  line-height: 1.4;
}

.lesson-item .lesson-meta {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
}

.video-indicator {
  color: #1890ff;
  margin-right: 4px;
}

.no-video-indicator {
  color: #999;
  margin-right: 4px;
}

.lesson-status {
  flex-shrink: 0;
  margin-left: 10px;
}

.learning-stats,
.quick-actions {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
}

.learning-stats h4,
.quick-actions h4 {
  margin-bottom: 16px;
  color: #333;
}

.stats-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  color: #666;
}

.stat-value {
  font-weight: bold;
  color: #1890ff;
}

.quick-actions .ant-btn {
  margin-bottom: 8px;
}

.quick-actions-circle {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: flex-start;
  gap: 48px;
  margin-bottom: 20px;
  padding: 0 16px;
}

.quick-action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.quick-actions-circle .ant-btn {
  width: 56px;
  height: 56px;
  font-size: 26px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.quick-action-label {
  margin-top: 8px;
  font-size: 15px;
  color: #333;
  text-align: center;
}

.notes-md-row {
  display: flex;
  gap: 24px;
}
.notes-md-editor {
  flex: 1;
  height: 400px;
}
.notes-md-preview-scroll {
  flex: 1;
  height: 400px;
  overflow: auto;
}
.notes-md-preview {
  flex: 1;
  background: #fafbfc;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  min-height: 200px;
  max-height: 400px;
  overflow: auto;
  padding: 0 8px 8px 8px;
}
</style>
